
Note: If you, at a later moment, want to experiment with bidirectional
bindings (for example between a data model property and a text field), this
could be modeled by using four of these entities: two producers, and two
receivers. This, as you can imagine, increases the code complexity
considerably — still, if you're in the mood to play, it can be fun.
The fundamental function of binding is bindTo(_:). To bind an observable to another
entity, the receiver must conform to ObserverType. This entity has been explained in
previous chapters: it’s a Subject which can process values, but can also be written
to manually. Subjects are extremely important when working with the imperative
nature of Cocoa, considering that the fundamental components such as UILabel,
UITextField, and UIImageView have mutable data that can be set or retrieved.
It’s important to remember that bindTo(_:) can also be used for other purposes —
not just to bind user interfaces to the underlaying data. For example, you could use
bindTo(_:) to create dependent processes, so that a certain observable would
trigger a subject to perform some background tasks without displaying anything on
the screen.
To summarize, bindTo(_:) is a special and tailored version of subscribe(_:): there
are no side effects or special cases when calling bindTo(_:).
Using binding observables to display data
Now that you know what bindings are, you can start to integrate them into your
app. In the process, you’ll make the whole code a little more elegant and turn the
search result into a reusable data source.
The first change to apply is to refactor the long observable that assigns the data to
the correct UILabel with subscribe(onNext:). Open ViewController.swift and in
viewDidLoad() replace the complete subscription code to searchCityName with:
let search = searchCityName.rx.text
.filter { ($0 ?? "").characters.count > 0 }
.flatMapLatest { text in
return ApiController.shared.currentWeather(city: text ?? "Error")
.catchErrorJustReturn(ApiController.Weather.empty)
}
.observeOn(MainScheduler.instance)
This change, specifically flatMapLatest, makes the search result reusable and
transforms a single-use data source into a multi-use Observable. The power of this
change will be covered later in the chapter dedicated to MVVM, but for now simply
realize that observables can be heavily reusable entities in Rx, and the correct
modeling can make a long, difficult-to-read, single-use observer into a multi-use
and easy to understand observer instead.
RxSwift - Reactive Programming with Swift Chapter 12: Beginning RxCocoa
raywenderlich.com 238